import {Card} from 'antd';
import React, {useEffect, useRef, useState} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import ProTable, {ActionType} from '@ant-design/pro-table';
import type {TableListItem} from './data.d';
import {queryGoodsGrid} from './service';
import {columnsSorter, columnToColumnsState, empty, NumberDiv} from "@/utils/function";
import {queryUse} from "@/utils/service";
import {getSelectList} from "@/pages/BTCList/getSelectList";
import cloneDeep from "lodash/cloneDeep";

let sorterGoodsGrid: any = null;
let dataCopyGoodsGrid: any = null;

const GoodsGrid: React.FC = () => {
  let columns: any[] = [
    {
      title: "币种",
      dataIndex: 'asset',
      key: 'asset',
      fixed: "left",
      width: 100,
      tip: '币种是唯一的 key',
    },
    {
      title: "划转数量",
      width: 120,
      dataIndex: 'transQty',
      sorter: true,
      key: 'transQty',
      renderText: (val: string | number) => NumberDiv(val, 1, 4)
    },
    {
      title: "现有数量",
      width: 120,
      dataIndex: 'qty',
      sorter: true,
      key: 'qty',
      renderText: (val: string | number) => NumberDiv(val, 1, 4)
    },
    {
      title: "当前价格",
      width: 120,
      dataIndex: 'price',
      sorter: true,
      key: 'price',
      renderText: (val: string | number) => NumberDiv(val, 1, 4)
    },
    {
      title: "币种盈亏",
      width: 120,
      dataIndex: 'assetProfit',
      sorter: true,
      key: 'assetProfit',
      renderText: (val: string | number) => NumberDiv(val, 1, 4)
    },
    {
      title: "USDT盈亏",
      width: 120,
      dataIndex: 'usdtProfit',
      sorter: true,
      key: 'usdtProfit',
      renderText: (val: string | number) => NumberDiv(val, 1, 4)
    },
  ];
  columnsSorter("GoodsGrid现货网格收益统计", columns);
  const [col, setCol] = useState<any>(columnToColumnsState(columns));
  const [dataTable, setDataTable] = useState<any>(null);
  const actionRef = useRef<ActionType>();
  useEffect(() => {
    getSelectList("8", "GoodsGrid", actionRef).then(
      (selectList: React.ReactNode) => {
        // debugger
        setDataTable(<ProTable<TableListItem>
          headerTitle={""}
          rowKey="key"
          bordered
          actionRef={actionRef}
          columnsStateMap={col}
          onColumnsStateChange={(e) => {
            if (!empty(e)) {
              localStorage.setItem("GoodsGrid现货网格收益统计", JSON.stringify(e));
              setCol(e);
            }
          }}
          toolBarRender={() => [
            <div>{selectList}</div>,
          ]}
          pagination={false}
          scroll={{y: 666}}
          search={false}
          request={async (params = {}, sort, filter) => {
            //console.log(sort, filter);

            let data;

            //dataCopy
            if (sorterGoodsGrid !== null && sort !== sorterGoodsGrid) {
              data = cloneDeep(dataCopyGoodsGrid);
              sorterGoodsGrid = (sort);
            } else {
              const msg = await queryGoodsGrid();
              data = queryUse(msg);
              dataCopyGoodsGrid = cloneDeep(data);
              sorterGoodsGrid = (sort);
            }

            //sort
            if (!empty(sort)) {
              const dataSort = (data: { sort: (arg0: (a: any, b: any) => void) => any; }, dataIndex: string, fg: boolean) =>
                data.sort((a, b) => {
                  return fg ? (a[dataIndex] - b[dataIndex]) : (b[dataIndex] - a[dataIndex]);
                })
              let dataIndex = '';
              let fg = true;
              for (let sortKey in sort) {
                dataIndex = sortKey;
                fg = (sort[sortKey] === 'ascend');
              }
              data = dataSort(data, dataIndex, fg);
            }

            let sumIds: any[] = [];
            //sum 'usdtProfit','assetProfit',
            let sumItem: any = {
              asset: "合计",
              usdtProfit: 0,
              // assetProfit: 0,
            }
            for (let i = 0; i < data.length; i++) {
              const item = data[i];
              sumItem.usdtProfit += (item.usdtProfit ? item.usdtProfit : 0);
              // sumItem.assetProfit += (item.assetProfit ? item.assetProfit : 0);
              // ids.push(item.id)
            }
            sumItem.id = sumIds;
            data.unshift(sumItem)

            if (data) {
              return {
                data: data,
                // success 请返回 true，
                // 不然 table 会停止解析数据，即使有数据
                success: true,
                // 不传会使用 data 的长度，如果是分页一定要传
                // total: number,
              };
            } else {
              return {
                data: data,
                success: false,
              };
            }
          }}
          columns={columns}
        />)
      });
  }, [col]);
  //处理同步数据

// debugger
  return (
    <PageContainer>
      <Card>
        {dataTable}
      </Card>
    </PageContainer>
  );
};

export default GoodsGrid;


